/*
 *    Copyright (c) 2006 ThoughtWorks, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.thoughtworks.turtlemock.internal;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ObjectOperation implements Operation {

    private final Map operationMap;

    public ObjectOperation(Class targetType) {
        this.operationMap = new HashMap();
        operationMap.put(Utils.getObjectToStringMethod(), new OperationToString(targetType));
        operationMap.put(Utils.getObjectHashCodeMethod(), new OperationHashCode(this));
        operationMap.put(Utils.getObjectEqualsMethod(), new OperationEquals());
    }

    public Object execute(Object proxy, Method method, Object[] args) throws Throwable {
        if (!operationMap.containsKey(method)) {
            throw new NoSuchMethodException(method.getName());
        }
        return ((Operation) operationMap.get(method)).execute(proxy, method, args);
    }

    private static class OperationEquals implements Operation {
        public Object execute(Object proxy, Method method, Object[] args) throws Throwable {
            return Boolean.valueOf(proxy == args[0]);
        }
    }

    private static class OperationHashCode implements Operation {
        private final Object key;

        public OperationHashCode(Object key) {
            this.key = key;
        }

        public Object execute(Object proxy, Method method, Object[] args) throws Throwable {
            return new Integer(key.hashCode());
        }
    }

    private static class OperationToString implements Operation {
        private final Class targetType;

        public OperationToString(Class targetType) {
            this.targetType = targetType;
        }

        public Object execute(Object proxy, Method method, Object[] args) throws Throwable {
            return targetType.getName() + " mock";
        }
    }

}
